package com.hjq.filter;

import com.hjq.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
// @WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        System.out.println(req.getRequestURL());
        if(req.getRequestURL().toString().contains("login")){
           chain.doFilter(request,response);
            return;
        }
        String token = req.getHeader("Token");
        if(token==null || token.isEmpty()){
            log.info("token 不存在");
            resp.setStatus(401);
            return;
        }else{
            try {
                Claims claims = JwtUtils.parseJWT(token);
                log.info("token解析后的结果:{}",claims);
            } catch (Exception e) {
                log.info("token 不合法");
                resp.setStatus(401);
                return;
            }
        }
        log.info("token 合法");
        chain.doFilter(request,response);

    }
}
